import requests
import time
import json

# 配置参数
product_id = "AN3Cn8YJxb"
device_name = "location"

# 定值鉴权信息
authorization = "version=2022-05-01&res=userid%2F426834&et=1746211223&method=sha1&sign=LgV%2BhCfx1osKknHuEOTWEkIUOZA%3D"

def query_device_property():
    url = "https://iot-api.heclouds.com/thingmodel/query-device-property"
    headers = {
        "Accept": "application/json, text/plain, */*",
        "Authorization": authorization
    }
    params = {
        "product_id": product_id,
        "device_name": device_name
    }

    try:
        # 获取当前时间并输出
        current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print(f"当前时间: {current_time}")

        response = requests.get(url, headers=headers, params=params)
        print("请求头:", headers)
        print("响应状态码:", response.status_code)
        print("响应内容:", response.text)

        # 解析 JSON 响应
        response_data = json.loads(response.text)

        # 提取 cur_location 的值
        if "data" in response_data:
            for item in response_data["data"]:
                if item["identifier"] == "cur_location":
                    cur_location = json.loads(item["value"])  # 解析 value 字段的 JSON 字符串
                    print("当前设备位置:", cur_location)
                    break
            else:
                print("未找到 cur_location 属性")
        else:
            print("响应中未包含 data 字段")

    except Exception as e:
        print(f"异常: {str(e)}")

if __name__ == "__main__":
    while True:
        query_device_property()
        time.sleep(5)


# import requests
# import time
# import hmac
# import base64
# from urllib.parse import quote_plus
#
# # 配置参数
# product_id = "AN3Cn8YJxb"
# device_name = "location"
# api_key = "WE05YXJUMFdWRHpoelNucGdHbHRUcm1qcmlHNFZKRXE="  # 严格检查此处是否与平台一致
#
#
# def generate_auth_header():
#     # 关键参数定义（需与官方文档一致）
#     version = "2022-05-01"
#     method = "sha1"
#     et = int(time.time()) + 3600  # 过期时间1小时
#     res = "userid/426834"  # 根据官方文档调整资源路径（此处为原始代码配置）
#
#     # 生成待签名字符串（按字典序排列参数）
#     signature_str = f"et={et}&method={method}&res={res}&version={version}"
#
#     # 计算HMAC-SHA1签名
#     signature = hmac.new(api_key.encode(), signature_str.encode(), "sha1").digest()
#     signature_b64 = base64.b64encode(signature).decode()
#     signature_encoded = quote_plus(signature_b64)  # URL编码
#
#     # 构建Authorization头
#     return {
#         "Content-Type": "application/json",
#         "Authorization": "version=2022-05-01&res=userid%2F426834&et=1746201139&method=sha1&sign=dKsTIDTaOwrouf2JN7HfrYhsJ%2Bs%3D"
#     }
#
#
# def send_request():
#     url = "https://iot-api.heclouds.com/thingmodel/query-device-property-detail"
#     data = {
#         "product_id": product_id,
#         "device_name": device_name,
#         "params": ["cur_location"]
#     }
#     try:
#         headers = generate_auth_header()
#         print("完整请求头:", headers)  # 打印Header供对比
#         response = requests.post(url, headers=headers, json=data)
#         if response.status_code == 200:
#             print("请求成功:", response.json())
#         else:
#             print(f"请求失败: {response.status_code} - {response.text}")
#     except Exception as e:
#         print(f"发生错误: {e}")
#
#
# # 执行请求
# send_request()




#
# import requests
# import time
# import json
#
# # 设置API请求的URL和头部
# url = "https://iot-api.heclouds.com/thingmodel/query-device-property-detail"
# headers = {
#     "Content-Type": "application/json",
#     "Authorization": "version=2022-05-01&res=userid%2F426834&et=1746197022&method=sha1&sign=WmcbW2q58JidqLgdCXxD731gjyU%3D"  # 如果需要授权，可以添加Bearer Token
# }
#
# # 请求的数据体
# data = {
#     "product_id": "AN3Cn8YJxb",
#     "device_name": "location",
#     "params": ["cur_location"]
# }
#
# # 定义发送请求的函数
# def send_request():
#     try:
#         # 发送POST请求
#         response = requests.post(url, headers=headers, data=json.dumps(data))
#         # 解析返回结果
#         if response.status_code == 200:
#             print("请求成功:", response.json())
#         else:
#             print(f"请求失败: {response.status_code} - {response.text}")
#     except Exception as e:
#         print(f"发生错误: {e}")
#
# # 每5秒发送一次请求
# while True:
#     send_request()
#     time.sleep(5)
